package com.link.base.base.opty.controller;

import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.activity.model.Activitys;
import com.link.base.base.activity.service.ActivityService;
import com.link.base.base.opty.model.Opty;
import com.link.base.base.opty.model.OptyItem;
import com.link.base.base.opty.service.OptyItemService;
import com.link.base.base.opty.service.OptyService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 商机请求处理
 */
@Controller
@RequestMapping("/link/opty")
public class OptyController extends BasicController<Opty> {

    @Resource
    private OptyService optyService;

    @Resource
    private ActivityService activityService;

    @Resource
    private AccountService accountService;

    @Resource
    private OptyItemService optyItemService;

    @Resource
    private OptyItemController OptyItemController;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Override
    public BasicService<Opty> getBasicService() throws Exception {
        return optyService;
    }

    /**
     * 深度复制商机
     */
    @RequestMapping(value = "/deepCopy/{id}")
    @ResponseBody
    public String deepCopy(@PathVariable Long id, @JsonParam QueryParams qps1, @JsonParam QueryParams qps2,
                           HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Opty record = new Opty();
        record.setId(id);
        try {
            record = optyService.queryById(record);
            record.setId(keyGenerateDao.keyGenerate());
            qps1.setPageFlag(false);
            qps2.setPageFlag(false);
            //产品信息列表插入
            Map<String, Object> map = OptyItemController.queryListPage(id, qps1, session, request, response);
            @SuppressWarnings("unchecked")
            List<OptyItem> proList = (List<OptyItem>) map.get("rows");
            for (OptyItem optyItem : proList) {
                optyItem.setId(keyGenerateDao.keyGenerate());
                optyItem.setRow_status("NEW");
                optyItem.setOptyId(record.getId());
                optyItemService.insert(optyItem);
            }
            //活动信息列表插入
            if (id == null) {
                throw new BasicControllerException("optyId 不能为空！");
            }
            qps2.addFilter(new Filter("optyId", String.valueOf(id)));
            Activitys t = (Activitys) BasicModel.transformClass(Activitys.class, qps2);
            List<Activitys> actlist = activityService.queryByExamplePage(t);
            for (Activitys activitys : actlist) {
                activitys.setId(keyGenerateDao.keyGenerate());
                activitys.setOptyId(record.getId());
                activityService.insert(activitys);
            }

            //标记
            record.setRow_status("NEW");
            request.setAttribute("opty", record);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return "opty/optyNew";
    }

    /**
     * 商机转订单
     */
    @RequestMapping(value = "/optyGenerateOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> optyGenerateOrder(@JsonParam Opty record, @JsonParam QueryParams qps, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            qps.setPageFlag(false);
            //产品信息列表插入
            Map<String, Object> map = OptyItemController.queryListPage(record.getId(), qps, session, request, response);
            @SuppressWarnings("unchecked")
            List<OptyItem> proList = (List<OptyItem>) map.get("rows");
            record.setProdList(proList);
            Long randomId = keyGenerateDao.keyGenerate();
            optyService.optyGenerateOrder(record, randomId);
            result.put("randomId", randomId);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryActivityPage", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryActivityPage(String optyId, @JsonParam QueryParams qps,
                                                 HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryActivityPage")
                .withMessage("查询商机活动列表信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (optyId == null || "".equals(optyId)) {
                throw new BasicControllerException("optyId 不能为空！");
            }
            qps.addFilter(new Filter("optyId", optyId));
            Activitys t = (Activitys) BasicModel.transformClass(Activitys.class, qps);
            List<Activitys> list = activityService.queryByExamplePage(t);
            result.put("success", true);
            result.put("total", getCount(t, list.size()));
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    @Override
    public void beforeImport(Opty record, HttpServletRequest request) {
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);
        qps.addFilter(new Filter("acctName", record.getAccnt()));
        Account entity = (Account) BasicModel.transformClass(Account.class, qps);
        try {
            List<Account> list = accountService.queryByExamplePage(entity);
            record.setAccntId(list.get(0).getId());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LCLogger.withException(e);
        }
    }

    @RequestMapping(value = "/queryOptyReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryOptyReport(@JsonParam QueryParams qps, @JsonParam Opty entity,
                                               HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryOptyReport")
                .withMessage("查询商机报表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            qps.setPageFlag(false);
            Opty record = (Opty) BasicModel.transformClass(entity.getClass(), qps);
            record.setLoginCorpId(qps.getLoginCorpId());
            String html = optyService.getOptyReportHtml(record);
            result.put("success", true);
            //result.put("total", list.size());
            result.put("html", html);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    @RequestMapping(value = "/queryOptyReportOrg", method = RequestMethod.POST)
    @ResponseBody
    public Object queryOptyReportOrg(@JsonParam QueryParams qps, @JsonParam Opty entity, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryOptyReportOrg")
                .withMessage("查询商机报表...").flush();
        List<Opty> list = null;
        try {
            Opty record = (Opty) BasicModel.transformClass(entity.getClass(), qps);
            record.setLoginCorpId(qps.getLoginCorpId());
//          List<Opty> list = optyService.queryOptyReportOrg(record);
            list = optyService.queryOptyReportOrgIdByName(record);
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getManagerOrgId() == null) {
                    list.remove(i);
                }
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return list;
    }

    /**
     * <p>根据月份成单率查询商机数据与总金额</p>
     *
     * @author yrf
     * @param record
     * @return
     */
    @RequestMapping("/queryCountAndAmountByMonthAndRate")
    @ResponseBody
    public Map<String, Object> queryCountAndAmountByMonthAndRate(Opty record) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("rows", optyService.queryCountAndAmountByMonthAndRate(record));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>根据赢单率查询下级组织商机各金额 </p>
     *
     * @author yrf
     * @param record
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryOrgAmountByRate")
    @ResponseBody
    public Map<String, Object> queryOrgAmountByRate(Opty record) throws Exception {

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("rows", optyService.queryOrgAmountByRate(record));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>商机top10，amount+attr_22</p>
     *
     * @author yrf
     * @param record
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryOptyTop10")
    @ResponseBody
    public Map<String, Object> queryOptyTop10(Opty record) {

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("rows", optyService.queryOptyTop10(record));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询商机报表
     *
     * @throws Exception
     */
    @RequestMapping("/getOptyList")
    @ResponseBody
    public Map<String, Object> getOptyList(@JsonParam QueryParams qps, @JsonParam Opty record, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response, String nameOrPhone) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        qps.preDealSecurity(request);
        Opty t = (Opty) BasicModel.transformClass(record, qps);
        //按条件查询商机list
        try {
            t.setAttr1(nameOrPhone);
            List<Opty> list = optyService.getOptyList(t);
            result.put("rows", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
        }

        return result;
    }

    /**
     * api调用 获取通过商机id获取商机
     * @param record 商机
     * @return
     */
    @RequestMapping("/getApiOpty")
    @ResponseBody
    public Map<String, Object> getApiOpty(Opty record) {

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("rows", optyService.getApiOpty(record.getId()));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
